package com.lagou.edu.factory;

import com.lagou.edu.annotation.Service;
import com.lagou.edu.service.TransferService;
import com.lagou.edu.service.impl.TransferServiceImpl;
import com.lagou.edu.utils.ClassUtil;
import com.lagou.edu.utils.pathutile;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;

/**
 * @author 应癫
 *
 * 工厂类，生产对象（使用反射技术）
 */
public class AnnotationBeanFactory<o> {

    /**
     * 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
     * 任务二：对外提供获取实例对象的接口（根据id获取）
     */

    private static Map<String,Object> map = new HashMap<>();  // 存储对象


    static {


        List<String> fileNames = new ArrayList<>();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        String path = "com.lagou.edu.annotation";
        String path1 = "com.lagou.edu.dao";
        String path2 = "com.lagou.edu.factory";
        String path3 = "com.lagou.edu.service.impl";
        String path4 =  "com.lagou.edu.utils";
        String packagePath = path.replace(".", "/");
        String packagePath1 = path1.replace(".", "/");
        String packagePath2 = path2.replace(".", "/");
        String packagePath3 = path3.replace(".", "/");
        String packagePath4 = path4.replace(".", "/");


        Set<Class<?>> AnnoclassSet = ClassUtil.getClassSet(packagePath);
        Set<Class<?>> classSetDao = ClassUtil.getClassSet(packagePath1);
        classSetDao.addAll(ClassUtil.getClassSet(packagePath2));
        classSetDao.addAll(ClassUtil.getClassSet(packagePath3));
        classSetDao.addAll(ClassUtil.getClassSet(packagePath4));

        //获取所有的注解名
        List<String> annNames = new ArrayList<>();
        for(Class  anno: AnnoclassSet){
            String[] annoStr = anno.getName().split("\\.");
            int length = annoStr.length;
            if(length > 1){
                annNames.add(annoStr[annoStr.length - 1]);
            }else if(length == 1){
                annNames.add(annoStr[0]);
            }
        }

//获取所有的类信息
/*        HashMap<String, String> classInfos = new HashMap<>();
        String classname = null;
            for (Class clazzDao : classSetDao) {
                String name2 = clazzDao.getName();
                String[] split = name2.split("\\.");
                int length = split.length;
                if (length > 1) {
                    classname = split[split.length - 1];
                    classInfos.put(classname, name2);
                } else if (length == 1) {
                    classname = split[0];
                    classInfos.put(classname, name2);
                }
            }*/

                //实例化对象
                for (Class daoClass : classSetDao) {
                    //遍历注解
                for (Class anno : AnnoclassSet) {
                        Annotation annotation = daoClass.getAnnotation(anno);
                        if (annotation != null) {
                            Class<? extends Annotation> name = annotation.annotationType();
                            String name1 = name.getName();
                            if (name1.contains("annotation.Service") || name1.contains("annotation.Dao") || name1.contains("annotation.Transation")||name1.contains("annotation.Component")) {
                                //通过反射实例化对象
                                Object o = null;
                                String classname = "";
                                try {
                                    o = daoClass.newInstance();
                                    String name2 = daoClass.getName();
                                    String[] split = name2.split("\\.");
                                    int length = split.length;
                                    if (length > 1) {
                                        classname = split[split.length - 1];
                                    } else if (length == 1) {
                                        classname = split[0];

                                    }
                                } catch (InstantiationException e) {
                                    e.printStackTrace();
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                                StringBuffer stringBuffer = new StringBuffer();
                                String substring = classname.substring(0, 1).toLowerCase();
                                stringBuffer.append(classname);
                                stringBuffer.delete(0,1);
                                String s = stringBuffer.insert(0, substring).toString();

                                map.put(s, o);
                            }
                        }
                    }

                }

//扫描加有autoware注解的类，对其成员变量注入对象
                    for (Class daoClass : classSetDao) {
                        for (Class anno : AnnoclassSet) {
                            Field[] declaredFields = daoClass.getDeclaredFields();
                            for (Field field : declaredFields){
                            if(field.isAnnotationPresent(anno)){
                                String classname = "";
                                String name = daoClass.getName();
                                String[] split = name.split("\\.");
                                int length = split.length;
                                if (length > 1) {
                                    classname = split[split.length - 1];
                                } else if (length == 1) {
                                    classname = split[0];
                                }
                                StringBuffer stringBuffer = new StringBuffer();
                                String substring = classname.substring(0, 1).toLowerCase();
                                stringBuffer.append(classname);
                                stringBuffer.delete(0,1);
                                String s = stringBuffer.insert(0, substring).toString();
                                Object o = map.get(s);
                                String ref = field.getName();
                                Object ref1 = map.get(ref);
                              field.setAccessible(true);
                                try {
                                    field.set(o,ref1);

                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                    }
                }
            }


                    //处理申明式事务注解
     /*   for (Class daoClass : classSetDao) {
            //遍历注解
            for (Class anno : AnnoclassSet) {
                Annotation annotation = daoClass.getAnnotation(anno);
                if (annotation != null) {
                    Class<? extends Annotation> name = annotation.annotationType();
                    String name1 = name.getName();
                    if (name1.contains("annotation.Transation")) {
                            //执行事务的代理对象
                        Object proxyFactory = map.get("proxyFactory");

                        Class<?> aClass = proxyFactory.getClass();
                        try {
                            Method getJdkProxy = aClass.getMethod("getJdkProxy", new Class[]{Object.class});

                            Object invoke = getJdkProxy.invoke(proxyFactory);
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }*/
















                    }




        Class<TransferServiceImpl> transferServiceClass = TransferServiceImpl.class;

        Class<Service> serviceClass = Service.class;

        //获取标注解的类
      /*  if (transferServiceClass.isAnnotationPresent(serviceClass)) {
            Service annotation = transferServiceClass.getAnnotation(serviceClass);
            System.out.println(annotation.value());
            transferServiceClass

            String clazz = element.attributeValue("class");  // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
            // 通过反射技术实例化对象
            Class<?> aClass = Class.forName(clazz);
            Object o = aClass.newInstance();  // 实例化之后的对象


        }*/



        //对这些类实例化
        //扫描属性值，将依赖注入的对象注入




    // 任务二：对外提供获取实例对象的接口（根据id获取）
    public static  Object getBean(String id) {
        return map.get(id);
    }




}
